package com.lzkj.raos.servlet;

import com.lzkj.raos.utils.CheckUtil;
import com.lzkj.raos.utils.MessageUtil;
import com.lzkj.raos.utils.WeixinUtil;
import org.dom4j.DocumentException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2021/3/22 20:13
 * 接入微信公众平台开发，开发者需要按照如下步骤完成：
 * 1、填写服务器配置，例如：http://qpjfr6.natappfree.cc/wx
 * URL组成 = 内网穿透到外网的域名 + 项目名 + 访问路径
 * 2、验证服务器地址的有效性
 * 3、依据接口文档实现业务逻辑
 */
@WebServlet("/wx")
public class WechatCheckServlet extends HttpServlet {

    /**
     * 参数及描述
     * signature：微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * timestamp：时间戳
     * nonce：随机数
     * echostr：随机字符串
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");
        PrintWriter writer = resp.getWriter();

        //校验，如何匹配则返回生成的随机字符串
        if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
            writer.print(echostr);
        }
    }

    /**
     * 对话开发为post请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        try {
            Map<String, String> map = MessageUtil.xmlToMap(req);
            String fromUserName = map.get("FromUserName");
            String toUserName = map.get("ToUserName");
            String msgType = map.get("MsgType");
            String content = map.get("Content");

            String message = null;
            if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {
                if ("1".equals(content)) {
                    message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.firstMenu());
                } else if ("2".equals(content)) {
                    message = MessageUtil.initNewsMessage(toUserName, fromUserName);
                } else if ("3".equals(content)) {
                    message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.threeMenu());
                } else if ("?".equals(content) || "？".equals(content)) {
                    message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
                } else if (content.startsWith("翻译")) {
                    String word = content.replaceAll("^翻译", "").trim();
                    if ("".equals(word)) {
                        message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.threeMenu());
                    } else {
                        message = MessageUtil.initText(toUserName, fromUserName, WeixinUtil.translate(word));
                    }
                }
            } else if (MessageUtil.MESSAGE_EVNET.equals(msgType)) {
                String eventType = map.get("Event");
                if (MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)) {
                    message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
                } else if (MessageUtil.MESSAGE_CLICK.equals(eventType)) {
                    message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
                } else if (MessageUtil.MESSAGE_VIEW.equals(eventType)) {
                    String url = map.get("EventKey");
                    message = MessageUtil.initText(toUserName, fromUserName, url);
                } else if (MessageUtil.MESSAGE_SCANCODE.equals(eventType)) {
                    String key = map.get("EventKey");
                    message = MessageUtil.initText(toUserName, fromUserName, key);
                }
            } else if (MessageUtil.MESSAGE_LOCATION.equals(msgType)) {
                String label = map.get("Label");
                message = MessageUtil.initText(toUserName, fromUserName, label);
            }
            System.out.println(message);

            out.print(message);
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }


}
